import { memo, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useLocation } from "react-use";
import { STORAGE_USERTOKEN_KEY } from "./consts";

/**
 * 路由鉴权
 *  - 自动跳转app/*
 */
function Auth(props: { children: React.ReactElement }) {
  const location = useLocation();
  const navigate = useNavigate();
  useEffect(() => {
    const tokenData = localStorage.getItem(STORAGE_USERTOKEN_KEY);
    const tokenInfo = tokenData ? JSON.parse(tokenData) : {};
    if (location.pathname?.startsWith('/app')) {
      //   // 无token信息或已超时
      //   if (!tokenInfo.token || Date.now() >= tokenInfo.expires) {
      //     navigate('/login');
      //   }
      // } else {
      //   if (tokenInfo.token && Date.now() < tokenInfo.expires) {
      //     console.log("............app");
      //     navigate('/app/home');
      //   }
      navigate('/app/home');
    }
  }, [])

  return props.children;
}

export default memo(Auth);
